import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/views/Layout.vue'
import Home from '@/views/Home.vue'
import Auth from '@/views/Auth.vue'
import ProductDetail from '@/views/ProductDetail.vue'
import Cart from '@/views/Cart.vue'
import OrderConfirm from '@/views/OrderConfirm.vue'
import OrderPay from '@/views/OrderPay.vue'
import Orders from '@/views/Orders.vue'
import OrderDetail from '@/views/OrderDetail.vue'
import Profile from '@/views/Profile.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: Layout,
      children: [
        {
          path: '',
          name: 'home',
          component: Home,
          meta: { title: '首页 - 小米有品' }
        },
        {
          path: 'product/:id',
          name: 'product-detail',
          component: ProductDetail,
          props: true,
          meta: { title: '商品详情 - 小米有品' }
        },
        {
          path: 'cart',
          name: 'cart',
          component: Cart,
          meta: { title: '购物车 - 小米有品' }
        },
        {
          path: 'order/confirm',
          name: 'order-confirm',
          component: OrderConfirm,
          meta: { title: '订单确认 - 小米有品', requiresAuth: true }
        },
        {
          path: 'order/pay/:orderId',
          name: 'order-pay',
          component: OrderPay,
          props: true,
          meta: { title: '订单支付 - 小米有品', requiresAuth: true }
        },
        {
          path: 'orders',
          name: 'orders',
          component: Orders,
          meta: { title: '我的订单 - 小米有品', requiresAuth: true }
        },
        {
          path: 'order/detail/:id',
          name: 'order-detail',
          component: OrderDetail,
          props: true,
          meta: { title: '订单详情 - 小米有品', requiresAuth: true }
        },
        {
          path: 'profile',
          name: 'profile',
          component: Profile,
          meta: { title: '个人信息 - 小米有品', requiresAuth: true }
        }
      ]
    },
    {
      path: '/auth',
      name: 'auth',
      component: Auth,
      meta: { title: '登录注册 - 小米有品' }
    },
    // 兼容旧的登录路由
    {
      path: '/login',
      redirect: '/auth'
    },
    {
      path: '/register',
      redirect: '/auth'
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title as string
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    if (!token) {
      next({ name: 'login', query: { redirect: to.fullPath } })
      return
    }
  }

  next()
})

export default router
